import { passwordLogin, codeLogin } from '@/api'
import { showFailToast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
    }
  },
  mutations: {
    setUserInfo (state, info) {
      state.userInfo = info
    }
  },
  actions: {
    // 登录
    async onLogin (context, payload) {
      let result = null
      if (payload.password) {
        result = await passwordLogin(payload)
      } else {
        result = await codeLogin(payload)
      }
      if (!result.data) {
        showFailToast(result.message)
        return
      }
      context.commit('setUserInfo', result.data)
      localStorage.setItem('userInfo', JSON.stringify(result.data))
    },
    // 退出登录
    outLogin (context) {
      context.commit('setUserInfo', {})
      localStorage.removeItem('userInfo')
    }
  }
}
